package org.geektimes.projects.user.web.controller;

import org.geektimes.web.mvc.controller.PageController;

import javax.servlet.AsyncContext;
import javax.servlet.AsyncEvent;
import javax.servlet.AsyncListener;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import java.io.IOException;

@Path("/async")
public class AsyncController implements PageController {
    /**
     * @param request  HTTP 请求
     * @param response HTTP 相应
     * @return 视图地址路径
     * @throws Throwable 异常发生时
     */
    @Override
    @GET
    @Path("/demo")
    public String execute(HttpServletRequest request, HttpServletResponse response) throws Throwable {
        if (request.isAsyncSupported()) {
            AsyncContext asyncContext = request.startAsync();
            asyncContext.start(new Runnable() {
                @Override
                public void run() {
                    System.out.println("AsyncContext.........");
                    try {
                        Thread.sleep(5000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });
            //设置超时
            asyncContext.setTimeout(3000);
            asyncContext.addListener(new AsyncListener() {
                @Override
                public void onComplete(AsyncEvent event) throws IOException {
                    System.out.println("完成....");
                }

                @Override
                public void onTimeout(AsyncEvent event) throws IOException {
                    System.out.println("超时....");
                }

                @Override
                public void onError(AsyncEvent event) throws IOException {
                    System.out.println("出现错误: " + event.getThrowable());
                }

                @Override
                public void onStartAsync(AsyncEvent event) throws IOException {
                    System.out.println("开始执行异步操作...");
                }
            });
        }
        return null;
    }
}
